import { Image, message, Popconfirm, Button } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import ProForm, {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
} from "@ant-design/pro-form";
import useCommonTable from "@/hooks/useCommonTable";
import { history } from "umi";
import {
  fetchList,
  cancelOrder_waitPay,
  cancelOrder_isPay,
  deliver_goods,
  getPullData,
} from "@/api/order";
import {
  orderNormalOptions,
  orderStatusOptions,
  nameListOptions,
} from "@/const";
import ScanRasCode from "./components/ScanRasCode";
import sendMsg2Print from "@/ws";
import { printTestData } from "@/printTest";

export default () => {
  const columns = [
    {
      title: "订单状态",
      dataIndex: "orderStatus",
      valueType: "select",
      fieldProps: {
        options: orderStatusOptions,
      },
      formItemProps: {
        initialValue: "0",
      },
    },
    {
      title: "订单号",
      dataIndex: "orderNum",
      search: false,
    },
    {
      title: "订单总金额",
      dataIndex: "amount",
      search: false,
      render: (_, record) => {
        return (
          <>
            <span>￥{record.amount}</span>
            {record.integralPrice && <span>+{record.integralPrice}积分</span>}
            <span> 运费：{record.freight || 0}</span>
          </>
        );
      },
    },
    {
      title: "商品信息",
      dataIndex: "shop",
      search: false,
      render: (_, record) => {
        return (
          <>
            {record.articlesVOS?.map((item, index) => {
              return (
                <div
                  key={item.id}
                  style={{ display: "flex", marginBottom: 10 }}
                >
                  <Image width={80} height={80} src={item.picture} />
                  <div style={{ marginLeft: 8 }}>
                    <div>{item.title}</div>
                    <div>￥{item.unitPrice}</div>
                    <div>{item.quantity}</div>
                  </div>
                </div>
              );
            })}
          </>
        );
      },
    },
    {
      title: "收货信息",
      dataIndex: "reciver",
      search: false,
      render: (_, record) => {
        return (
          <>
            <div>姓名：{record.userName}</div>
            <div>手机号：{record.phoneNum}</div>
            <div>
              收货地址：
              {record.province}
              {record.city}
              {record.area}
              {record.detail}
            </div>
          </>
        );
      },
    },

    {
      title: "订单类型",
      dataIndex: "orderNormal",
      valueType: "select",
      fieldProps: {
        options: orderNormalOptions,
      },
    },
    {
      title: "用户名称",
      dataIndex: "userName",
      hideInTable: true,
    },
    {
      title: "用户手机号",
      dataIndex: "phoneNum",
      hideInTable: true,
    },

    {
      title: "下单时间",
      dataIndex: "createTime",
      search: false,
    },
  ];

  const renderSendModal = (record, actionRef) => {
    /* orderType 1=书籍 2=周边 3=积分 4=购物车 */
    /* articlesCategory 1=书籍 2=周边 */

    /* 1. orderType=1 直接展示芯片码*/
    /* 2. orderType=3 判断 articlesVOS 里面有articlesCategory=1的书籍 数量：quantity 展示芯片码*/
    /* 3. orderType=4 判断 articlesVOS 里面有articlesCategory=1的书籍 数量：quantity 展示芯片码*/

    let showCode = record.orderType == 1;
    if (record.orderType == 3 || record.orderType == 4) {
      showCode = record.articlesVOS?.some((item) => item.articlesCategory == 1);
    }
    // 能扫码的最大数量
    const quantity = record.articlesVOS
      ?.map((item) => item.quantity)
      .reduce((a, b) => a + b);

    return (
      <ModalForm
        title="发货"
        trigger={<Button type="primary">发货</Button>}
        onFinish={async (values) => {
          const res = await deliver_goods({
            orderId: record.orderId,
            addressId: record.addressId,
            orderCategory: record.orderType,
            ...values,
          });
          if (res.data) {
            message.success("发货成功");
            actionRef.current?.reload();
          }
        }}
      >
        <ProFormSelect
          name="name"
          label="商品描述"
          allowClear
          fieldProps={{
            options: nameListOptions,
          }}
          rules={[{ required: true, message: "请选择商品描述" }]}
        />
        <ProFormDigit
          label="包裹数量"
          name="quantity"
          placeholder="请输入包裹数量"
          min={1}
          rules={[{ required: true, message: "请输入包裹数量" }]}
        />

        {showCode && (
          <ProForm.Item
            label="芯片码"
            name="rasCodeList"
            rules={[{ required: true, message: "请扫码芯片码" }]}
          >
            <ScanRasCode quantity={quantity} />
          </ProForm.Item>
        )}
      </ModalForm>
    );
  };

  return (
    <PageContainer>
      {useCommonTable({
        title: "",
        renderAdd: () => {},
        columns,
        modalWidth: 400,
        fetchList,
        actionColumnWidth: 280,
        showCheckbox: false,
        renderAction: (_, record, renderModalForm, actionRef) => {
          // status: 订单状态 0:全部订单 1:待支付 2:待发货 3:待收货 4:已完成 5:已取消 6:售后中 7:已售后
          return (
            <>
              <Button
                style={{ marginRight: 8 }}
                onClick={() => {
                  history.push(
                    `/order/mall/detail?orderId=${record.orderId}&orderCategory=${record.orderType}`
                  );
                }}
              >
                详情
              </Button>
              {(record.orderStatus == 1 || record.orderStatus == 2) && (
                <Popconfirm
                  key="remove"
                  title="确定取消订单?"
                  onConfirm={async () => {
                    const func = {
                      1: cancelOrder_waitPay, // 未付款的取消订单
                      2: cancelOrder_isPay, // 已付款（未发货）的取消订单
                    };
                    const carData = {};
                    record?.articlesVOS.forEach((item) => {
                      carData[item.articlesId] = item.quantity;
                    });
                    const res = await func[record.orderStatus]({
                      carData,
                      orderId: record.orderId,
                      orderNum: record.orderNum,
                      orderType: record.orderType,
                      quantity: record.articlesVOS?.[0]?.quantity, // 直接购买需要传
                      refundType: 0, // 退款方式：0:全部退款 1:部分退款 支持商户自定义退款金额,但不得大于订单总金额
                    });
                    if (res.data) {
                      message.success("取消成功");
                      actionRef.current?.reload();
                    }
                  }}
                >
                  <Button type="danger" style={{ marginRight: 8 }}>
                    取消订单
                  </Button>
                </Popconfirm>
              )}
              {record.orderStatus == 2 && renderSendModal(record, actionRef)}
              {record.orderStatus == 8 && (
                <>
                  <Popconfirm
                    key="remove"
                    title="确定打印运单?"
                    onConfirm={async () => {
                      const res = await getPullData({
                        orderId: record.orderId,
                      });
                      if (res.data) {
                        // webSocket 调起打印
                        sendMsg2Print(res.data);
                        message.success("打印成功");
                        actionRef.current?.reload();
                      }
                    }}
                  >
                    <Button type="primary" style={{ marginRight: 8 }}>
                      打印运单
                    </Button>
                  </Popconfirm>
                </>
              )}
            </>
          );
        },
      })}
    </PageContainer>
  );
};
